﻿using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ICodeShare.UI.Converters
{
    /// <summary>
    /// 从矩形圆角中创建一个新的矩形圆角转换器
    /// </summary>
    [ValueConversion(typeof(CornerRadius), typeof(CornerRadius))]
    public sealed class CornerRadiusToCornerRadiusConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is CornerRadius))
            {
                return DependencyProperty.UnsetValue;
            }

            var source = (CornerRadius)value;

            var parameters = parameter as string;
            if (parameters != null)
            {
                var propertyNames = parameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (propertyNames.Length > 0)
                {
                    var cornerRadius = new CornerRadius(0.0);

                    var changed = false;

                    foreach (var propertyName in propertyNames)
                    {
                        switch (propertyName.Trim().ToLower())
                        {
                            case "topleft":
                                cornerRadius.TopLeft = source.TopLeft;
                                changed = true;
                                break;
                            case "topright":
                                cornerRadius.TopRight = source.TopRight;
                                changed = true;
                                break;
                            case "bottomright":
                                cornerRadius.BottomRight = source.BottomRight;
                                changed = true;
                                break;
                            case "bottomleft":
                                cornerRadius.BottomLeft = source.BottomLeft;
                                changed = true;
                                break;
                        }
                    }

                    if (changed)
                    {
                        return cornerRadius;
                    }
                }
            }

            return new CornerRadius(source.TopLeft, source.TopRight, source.BottomRight, source.BottomLeft);
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Contract.Ensures(false);
            throw new NotSupportedException();
        }
    }
}
